<?php

namespace App\Services\Repo;

use App\Models\AcceptRecord;
use App\Services\Interfaces\RepoServiceInterface;
use Illuminate\Database\Eloquent\Model;

class AcceptRecordRepo implements RepoServiceInterface
{
    /**
     * @param array|null $_options
     * @return Model
     * <code>
     *  $repo->create(['name' => '']);
     * </code>
     */
    public function create(array $_options = null):Model
    {
        // 没有被认领, 可以认领
        $accept_record = AcceptRecord::where(['project_id' => $_options['project_id']
            , 'user_id' => $_options['user_id']])
            ->first();
        if (empty($accept_record)) {
            // 新建一条记录
            $acceptRecord = new AcceptRecord();
            $acceptRecord->company_id = $_options['company_id'];
            $acceptRecord->project_id = $_options['project_id'];
            $acceptRecord->user_id = $_options['user_id'];
            $acceptRecord->customers = array($_options['customer_id']);
            $acceptRecord->save();
            return $acceptRecord;
        } else {
            $customer_arr = $accept_record->customers;
            array_push($customer_arr, $_options['customer_id']);
            $accept_record->customers = $customer_arr;
            $accept_record->save();
            return $accept_record;
        }
    }

    public function read($limit = 0)
    {

    }

    public function find(array $_filter):Model
    {

    }

    public function update(array $_filter, array $_update_data):bool
    {
        $acceptRecord = AcceptRecord::find($_filter)->first();
        $from = $_update_data['user']['from'];
        $formUser = AcceptRecord::where('user_id', $from)->first();
        $fromCustomers = $formUser->customers;
        $oldCustomers = $acceptRecord->customers;
        $type = $_update_data['user']['type'];
        $customers = $_update_data['customer_id'];
        // mv 代表转移
        if ($type === AcceptRecord::MV) {
            $customers = array_merge($oldCustomers, $customers);
            $acceptRecord->customers = $customers;
            $formUser->customers = array_values(array_diff($fromCustomers, $customers));
            $formUser->save();
            return $acceptRecord->save();
        }
        // cp 代表复制
        if ($type === AcceptRecord::CP) {
            $customers = array_merge($oldCustomers, $customers);
            $acceptRecord->customers = array_unique($customers);
            return $acceptRecord->save();
        }
    }

    public function delete(array $_filter):bool
    {
        // TODO: Implement delete() method.
    }
}